import classNames from 'classnames'
import React from 'react'
import './index.scss'
import { ConfigContext } from './ConfigProvider'
export type SizeType = 'large' | 'middle' | 'small' | 'default' | number
export interface SpaceProps extends React.HTMLAttributes<HTMLDivElement> {
  className?: string
  style?: React.CSSProperties
  size?: SizeType | SizeType[]
  direction?: 'horizontal' | 'vertical'
  split?: React.ReactNode
  align?: 'start' | 'end' | 'center' | 'baseline'
  wrap?: boolean
}
const Space: React.FC<SpaceProps> = (props) => {
  const { space } = React.useContext(ConfigContext)
  console.log(
    '%c [ space ]-17',
    'font-size:13px; background:pink; color:#bf2c9f;',
    space
  )
  const {
    className,
    style,
    align,
    size = space?.size || 'small',
    wrap = false,
    direction = 'horizontal',
    ...otherProps
  } = props

  const spaceSize = {
    small: 8,
    middle: 16,
    large: 24
  }

  function getNumberSize(size: SizeType) {
    return typeof size === 'string'
      ? (spaceSize as Record<SizeType, number>)[size]
      : size || 0
  }

  const mergedAlign =
    direction === 'horizontal' && align === undefined ? 'center' : align
  const cn = classNames('space', `space-${direction}`, {
    [`space-align-${mergedAlign}`]: mergedAlign
  })
  const otherStyles: React.CSSProperties = {}
  const childNodes = React.Children.toArray(props.children)
  const [horizontalSize, verticalSize] = React.useMemo(
    () =>
      ((Array.isArray(size) ? size : [size, size]) as [SizeType, SizeType]).map(
        (item) => getNumberSize(item)
      ),
    [size]
  )

  otherStyles.columnGap = horizontalSize
  otherStyles.rowGap = verticalSize

  const nodes = childNodes.map((child: any, i) => {
    const key = (child && child.key) || `space-item-${i}`

    return (
      <div className="space-item" key={key}>
        {child}
      </div>
    )
  })
  if (wrap) {
    otherStyles.flexWrap = 'wrap'
  }
  return (
    <div className={cn} style={{ ...style, ...otherStyles }} {...otherProps}>
      {nodes}
    </div>
  )
}

export default Space
